﻿using System;
using System.Collections.Concurrent;
namespace HB.Base
{
    /// <summary>
    /// 频率访问控制
    /// </summary>
    public class FrequencyFilter
    {
        static FrequencyFilter()
        {
            Dic = new ConcurrentDictionary<string, DateTime>();
        }
        static ConcurrentDictionary<string, DateTime> Dic = null;
        /// <summary>
        /// 申请运行
        /// </summary>
        /// <param name="Id">运行id</param>
        /// <param name="Interval">希望的间隔（s）</param>
        /// <returns></returns>
        public static bool ApplyForRun(string Id, double Interval)
        {
            if (GetLastestRunningTimeInterval(Id) > Interval)
            {
                UpdateRunning(Id);
                return true;
            }
            else
            {
                return false;
            }
        }
        static void UpdateRunning(string Id)
        {
            if (Id == null) { Id = ""; }

            if (Dic.ContainsKey(Id))
            {
                Dic[Id] = DateTime.Now;
            }
            else
            {
                Dic[Id] = DateTime.Now;
            }
        }

        static double GetLastestRunningTimeInterval(string Id)
        {
            if (Id == null) { Id = ""; }
            if (Dic.ContainsKey(Id))
            {
                return (DateTime.Now - Dic[Id]).TotalSeconds;
            }
            else
            {
                return double.MaxValue;
            }
        }
    }
}
